import React, { useState, useEffect, useCallback } from 'react';
import { Button, Divider, Input, Select, notification, Form, Card, Typography } from 'antd';
import { SaveOutlined, RadiusBottomrightOutlined, LoadingOutlined } from '@ant-design/icons';
import useStore from '../../../components/useStore';
import request from '../../../untils/request';

// 表单布局配置
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const { Title, Text } = Typography;

const AddMenuForm = () => {
  const { collapsed } = useStore();
  const [firstMenus, setFirstMenus] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  // 查询可新增的父级菜单
  const getFirstMenu = useCallback(async () => {
    try {
      const data = await request("/admin/menu/selectFirstMenus", {
        method: 'GET',
        mode: 'cors',
      });
      
      const formattedMenus = data.map(menu => ({
        value: menu.id,
        label: menu.title
      }));
      
      // 添加空白选项表示一级菜单
      formattedMenus.push({ value: null, label: "（无 - 作为一级菜单）" });
      setFirstMenus(formattedMenus);
    } catch (error) {
      notification.error({ message: "获取父级菜单失败" });
    }
  }, []);

  // 初始化时获取父级菜单列表
  useEffect(() => {
    getFirstMenu();
  }, [getFirstMenu]);

  // 表单提交处理
  const handleSubmit = async () => {
    try {
      // 表单验证
      const values = await form.validateFields();
      setLoading(true);

      const data = await request("/admin/menu/insert", {
        method: 'POST',
        mode: 'cors',
        body: {
          menu: {
            title: values.title,
            path: values.path,
            parent_menu_id: values.parent_menu_id
          }
        }
      });
      
      if (data.code === 200) {
        notification.success({ message: data.msg || "菜单新增成功" });
        form.resetFields(); // 重置表单
      } else {
        notification.error({ message: data.msg || "菜单新增失败" });
      }
    } catch (error) {
      notification.error({ message: "新增失败，请检查表单是否填写完整！" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      height: "94%",
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "auto",
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      fontSize: "0.8rem"
    }}>
      <Card 
        title={<Title level={5}>新增菜单</Title>}
        style={styles.container}
        bordered={false}
        className="shadow-sm"
      >
        <Text type="warning" style={{ marginBottom: 16, display: 'block' }}>
          以下所填写的内容均有长度限制！且新增的自定义菜单不得挂靠于系统内置菜单上。
        </Text>
        
        <Divider style={{ margin: '16px 0' }} />
        
        <Form
          form={form}
          layout="horizontal"
          {...formItemLayout}
          initialValues={{ parent_menu_id: null }}
        >
          <Form.Item
            name="title"
            label="菜单名称"
            rules={[
              { required: true, message: '请输入菜单名称' },
              { pattern: /^[^\s]{2,20}$/, message: '菜单名称不能包含空格，长度2-20字符' }
            ]}
          >
            <Input 
              showCount 
              maxLength={20} 
              addonBefore={<RadiusBottomrightOutlined />} 
              placeholder="请输入菜单名称"
            />
          </Form.Item>

          <Form.Item
            name="path"
            label="菜单路径"
            rules={[
              { required: true, message: '请输入菜单路径' },
              { pattern: /^[\/a-zA-Z]{2,100}$/, message: '路径只能包含字母和斜杠，长度2-100字符' }
            ]}
            extra="菜单路径需为字符/与英文字母组成"
          >
            <Input 
              showCount 
              maxLength={50} 
              placeholder="请输入菜单路径"
            />
          </Form.Item>

          <Form.Item
            name="parent_menu_id"
            label="父级菜单"
            extra="当前系统仅支持两级菜单"
          >
            <Select 
              placeholder="选择父级菜单" 
              style={{ width: '100%' }} 
              options={firstMenus}
              allowClear
            />
          </Form.Item>
        </Form>

        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <Button 
            type="primary" 
            onClick={handleSubmit}
            loading={loading}
            icon={loading ? <LoadingOutlined /> : <SaveOutlined />}
            style={styles.submitButton}
          >
            新增
          </Button>
        </div>

        <Divider style={{ margin: '24px 0 16px' }} />
        
        <Text type="secondary" style={{ fontSize: '0.8rem' }}>
          自定义菜单对于超级管理员永远可见，对于系统默认用户永远不可见！其他角色请自行配置。
        </Text>
      </Card>
    </div>
  );
};

const styles = {
  container: {
    width: "96%",
    margin: "2vh auto",
    padding: "20px",
  },
  submitButton: {
    width: "120px",
    height: "36px",
    fontSize: "0.9rem",
  }
};

export default AddMenuForm;
